import React, { useState, useRef,useEffect } from 'react'
import  './index.less'
interface TabItem {
  key: string
  value: string
}
interface tabProps {
  activeTab: String // 选中的标签,
  tabs: TabItem[]
  handleTabChange?: (tab: TabItem) => void // 点击标签时的回调
}

const CustomTabs: React.FC<tabProps> = ({ tabs, activeTab,  handleTabChange = () => {} }) => {
  const itemRefs = useRef<HTMLDivElement[]>([])
  const moveBlockRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    console.log('useEffect', itemRefs.current[0].clientWidth)
    moveBlockRef.current && (moveBlockRef.current.style.width = `${itemRefs.current[0].clientWidth+16}px`
    )
  }, [])
  const onHandleTabChange = (index: number, tab: TabItem) => {
    console.log('点击了', index, itemRefs.current[index].offsetLeft)
    if (moveBlockRef.current && itemRefs.current[index]) {
        moveBlockRef.current.style.width = `${itemRefs.current[index].clientWidth+16}px`
      moveBlockRef.current.style.transform = `translateX(${itemRefs.current[index].offsetLeft}px)`
    }
    handleTabChange(tab) // 调用外部传入的回调函数
  }
  return (
    <div className='tabBar'>
      <div className='tabBarBox'>
        <div ref={moveBlockRef} className='moveBlock'></div>
        {tabs.map((tab: TabItem, index) => (
          <div
            ref={el => {
              if (el) itemRefs.current[index] = el
            }}
            key={index}
            className={`tabBarItem ${activeTab === tab.key ? 'active' : ''}`}
            onClick={() => onHandleTabChange(index, tab)}
          >
            {tab.value}
          </div>
        ))}
      </div>
    </div>
  )
}
export default CustomTabs
